//
//  AddressMapFoodViewController.swift
//  iFoodMacau
//
//  Created by ning on 2018/9/4.
//  Copyright © 2018年 CYCON.com. All rights reserved.
//
//地图上的美食
import UIKit

class AddressMapFoodViewController: UIViewController {
    @IBOutlet weak var bmkMapView: UIView!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var tableViewTopLayoutConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgViewTopLayoutConstraint: NSLayoutConstraint!
    @IBOutlet weak var searchViewTopLayoutConstraint: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var headView: UIView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var searchView: UIView!
    @IBOutlet weak var relocationButton: UIButton!
    //自制导航栏
    @IBOutlet weak var navigationView: UIView!
    //标题
    @IBOutlet weak var navigationTitleLabel: UILabel!
    //导航栏距离顶部
    @IBOutlet weak var navigationViewTopLayoutConstraint: NSLayoutConstraint!
    //导航栏高
    @IBOutlet weak var navigationViewHeightLayoutConstraint: NSLayoutConstraint!
    //tableview的最终y坐标
    var tableViewOrginY: CGFloat = 0
    
    var addressArr = [String]() {
        didSet {
            if addressArr.count > 0 {
                UIView.animate(withDuration: 0.3) { [weak self] in
                    guard let strongSelf = self else { return }
                    strongSelf.tableViewOrginY = UIScreen.main.bounds.height / 2
                    strongSelf.tableView.frame.origin = CGPoint.init(x: 0, y: UIScreen.main.bounds.height / 2)
                    strongSelf.updateView(strongSelf.tableViewOrginY)
                }
            }
        }
    }
    //tableview是否可以滑动，默认不可滑动，防止与拖拽手势冲突，tableview完全显示后才可以滑动
    var isCanScroll = false
    var safeAreaInsetsBottom: CGFloat = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigateView()
        setupMapView()
        setupView()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewSafeAreaInsetsDidChange() {
        if #available(iOS 11.0, *) {
            super.viewSafeAreaInsetsDidChange()
             safeAreaInsetsBottom = self.view.safeAreaInsets.bottom
        } else {
            safeAreaInsetsBottom = 0
        }
       
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    //搜索栏的返回
    @IBAction func didBackButtonTouchUpInside(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    //地图上的美食导航返回
    @IBAction func didNavigateBackButtonTouchUpInside(_ sender: UIButton) {
        UIView.animate(withDuration: 0.3) { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.tableViewOrginY = UIScreen.main.bounds.height / 2
            strongSelf.tableView.frame.origin = CGPoint.init(x: 0, y: UIScreen.main.bounds.height / 2)
            strongSelf.updateView(strongSelf.tableViewOrginY)
        }
    }
    //搜索
    @IBAction func didSearchButtonTouchUpInside(_ sender: UIButton) {
        
    }
    //定位
    @IBAction func didRelocationButtonTouchUpInside(_ sender: UIButton) {
         addressArr = ["","","","","",""]
    }
    //更多
    @IBAction func didMoreButtonTouchUpInside(_ sender: UIButton) {
        UIView.animate(withDuration: 0.3) { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.tableViewOrginY = UIScreen.main.bounds.height / 2
            strongSelf.tableView.frame.origin = CGPoint.init(x: 0, y: UIScreen.main.bounds.height / 2)
            strongSelf.updateView(strongSelf.tableViewOrginY)
        }
    }
    func getTopBarHeight() -> CGFloat {
        return UIApplication.shared.statusBarFrame.height + 44
    }
}
///MARK:--Setup
extension AddressMapFoodViewController {
    fileprivate func setupNavigateView() {
        navigationViewHeightLayoutConstraint.constant = getTopBarHeight()
        navigationViewTopLayoutConstraint.constant = -getTopBarHeight()
        navigationTitleLabel.text = "地图上的美食"
    }
    
    func setupView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView()
        let pan = UIPanGestureRecognizer.init(target: self, action: #selector(didMapViewPan))
        pan.delegate = self
        tableView.addGestureRecognizer(pan)
        tableViewTopLayoutConstraint.constant = UIScreen.main.bounds.height
        tableViewOrginY = UIScreen.main.bounds.height
        moreView.alpha = 0
        bgViewTopLayoutConstraint.constant = 0
        searchViewTopLayoutConstraint.constant = UIApplication.shared.statusBarFrame.height
        moreView.frame.size = CGSize.init(width: UIScreen.main.bounds.width, height: UIApplication.shared.statusBarFrame.height + 30)
    }
    
    //地图
    fileprivate func setupMapView() {
        addressArr = ["","","","","","","","","","","","","","","","","","","","",""]
    }
}

extension AddressMapFoodViewController {
    //定位
    func doLocation() {
       
    }
    
    //搜索(此处应该请求后台数据)
    func doSearch() {
       
    }
}
//拖拽手势响应
extension AddressMapFoodViewController {
    @objc func didMapViewPan(pan: UIPanGestureRecognizer) {
        let point = pan.translation(in: tableView)
        let y = tableView.frame.origin.y
        switch pan.state {
        case .changed:
            updateView(y)
            tableView.frame.size = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

            //可移动范围内移动
            if y >= 0 && y <= UIScreen.main.bounds.height - headView.frame.height - safeAreaInsetsBottom {
                pan.view?.center = CGPoint.init(x: (pan.view?.center.x ?? 0) , y: (pan.view?.center.y ?? 0) + point.y)
                //重置
                pan.setTranslation(CGPoint.zero, in: tableView)
            }
            //超出可移动范围时，根据拖动方向而定
            if (y <= 0 && point.y >= 0) || (y >= UIScreen.main.bounds.height - headView.frame.height - safeAreaInsetsBottom && point.y <= 0){
                pan.view?.center = CGPoint.init(x: (pan.view?.center.x ?? 0) , y: (pan.view?.center.y ?? 0) + point.y)
                pan.setTranslation(CGPoint.zero, in: tableView)
            }
        case .ended:
            isCanScroll = false
            moreView.alpha = 0
            if y > tableViewOrginY{//向下：y为tableview的y坐标，坐标0点始终在页面顶部
                //超过中间部分，则拖动最终位置停在底部
                if  y > UIScreen.main.bounds.height / 2 {
                    pan.view?.frame.origin = CGPoint.init(x: 0, y: UIScreen.main.bounds.height - headView.frame.height - safeAreaInsetsBottom)
                    UIView.animate(withDuration: 0.3) { [weak self] in
                        self?.moreView.alpha = 1
                    }
                }else {//小于等于中间部分，则拖动最终位置停在中间
                    pan.view?.frame.origin =  CGPoint.init(x: 0, y: UIScreen.main.bounds.height / 2)
                    tableView.setContentOffset(CGPoint.zero, animated: false)

                }
            }else {//向上拖拽
                //小于中间部分，则拖动最终位置停在顶部
                if  y < UIScreen.main.bounds.height / 2 {
                    pan.view?.frame.origin = CGPoint.init(x: 0, y: navigationView.frame.height - headView.frame.height)
                    isCanScroll = true
                    pan.view?.frame.size = CGSize.init(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - safeAreaInsetsBottom - 10)
                }else {
                    pan.view?.frame.origin =  CGPoint.init(x: 0, y: UIScreen.main.bounds.height / 2)
                    tableView.setContentOffset(CGPoint.zero, animated: false)

                }
            }
            pan.setTranslation(CGPoint.zero, in: tableView)
            moreView.frame.size = CGSize.init(width: UIScreen.main.bounds.width, height: safeAreaInsetsBottom + headView.frame.height)
            tableViewOrginY = tableView.frame.origin.y
            updateView(tableViewOrginY)
        default:
            break
        }
        
    }
}
//随着拖拽手势，更新对应视图坐标
extension AddressMapFoodViewController {
    //更新视图的位置
    func updateView(_ tableViewY: CGFloat) {
        //定位按钮
        if tableViewY >= UIScreen.main.bounds.height / 4 {
            relocationButton.frame.origin = CGPoint.init(x: tableView.frame.origin.x + 10, y: tableView.frame.origin.y - 10 - relocationButton.frame.height)
        }else {
            relocationButton.frame.origin = CGPoint.init(x: tableView.frame.origin.x + 10, y: UIScreen.main.bounds.height / 4 + relocationButton.frame.height)
        }
        //搜索返回显示判断
        if  tableViewY > UIScreen.main.bounds.height / 4 {
            UIView.animate(withDuration: 0.3) { [weak self] in
                guard let strongSelf = self else { return }
                strongSelf.searchView.frame.origin = CGPoint.init(x: strongSelf.searchView.frame.origin.x, y: UIApplication.shared.statusBarFrame.height)
            }
        }else {
            UIView.animate(withDuration: 0.3) { [weak self] in
                guard let strongSelf = self else { return }
                strongSelf.searchView.frame.origin = CGPoint.init(x: strongSelf.searchView.frame.origin.x, y: UIApplication.shared.statusBarFrame.height - tableViewY)
            }
        }
        //导航栏显示/隐藏
        if  tableViewY > navigationView.frame.height  {
            UIView.animate(withDuration: 0.3) {[weak self] in
                guard let strongSelf = self else { return }
                strongSelf.navigationView.frame.origin = CGPoint.init(x: strongSelf.navigationView.frame.origin.x, y: 0 - tableViewY)
            }
        }else {
            UIView.animate(withDuration: 0.3) { [weak self] in
                guard let strongSelf = self else { return }
                strongSelf.navigationView.frame.origin = CGPoint.init(x: strongSelf.navigationView.frame.origin.x, y: 0)
            }
        }
        //更多商家显示判断
        if  tableViewY < (UIScreen.main.bounds.height - headView.frame.height - UIApplication.shared.statusBarFrame.height + 20 - safeAreaInsetsBottom)  {
            UIView.animate(withDuration: 0.1) { [weak self] in
                self?.moreView.alpha = 0
            }
        }else {
            UIView.animate(withDuration: 0.1) { [weak self] in
                self?.moreView.alpha = 1
            }
        }
    }
}

// MARK: - UIGestureRecognizerDelegate
extension AddressMapFoodViewController: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive press: UIPress) -> Bool {
        return !isCanScroll
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        return !isCanScroll
    }
}
// MARK: - Delegate, Datasource of tableview
extension AddressMapFoodViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 81
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return addressArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "AddressMapFoodTableViewCell") else {
            return UITableViewCell()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
}
// MARK: -UIScrollViewDelegate
extension AddressMapFoodViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset
        if offset.y < 0 {
            isCanScroll = false
        }
    }
}
